package com.example.demo.ssh;

import lombok.SneakyThrows;
import org.apache.sshd.common.file.nativefs.NativeFileSystemFactory;
import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.auth.AsyncAuthException;
import org.apache.sshd.server.auth.password.PasswordAuthenticator;
import org.apache.sshd.server.auth.password.PasswordChangeRequiredException;
import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
import org.apache.sshd.server.session.ServerSession;
import org.apache.sshd.server.shell.ProcessShellCommandFactory;
import org.apache.sshd.server.shell.ProcessShellFactory;
import org.apache.sshd.sftp.server.SftpSubsystemFactory;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;

public class SftpServer {

    public static void main(String args[]) throws IOException, InterruptedException {
        SshServer sshd = SshServer.setUpDefaultServer();
        sshd.setPort(2222);
        sshd.setHost("192.168.84.1");
        SftpSubsystemFactory factory = new SftpSubsystemFactory.Builder().build();
        sshd.setSubsystemFactories(Collections.singletonList(factory));
        sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
            @SneakyThrows
            @Override
            public boolean authenticate(String userName, String password, ServerSession serverSession) throws PasswordChangeRequiredException, AsyncAuthException {
                sshd.setFileSystemFactory(new VirtualFileSystemFactory(Paths.get("F:\\")));
             /*   NativeFileSystemFactory 取自user.dir 目录
                NativeFileSystemFactory nativeFileSystemFactory = NativeFileSystemFactory.INSTANCE;
                nativeFileSystemFactory.setUsersHomeDir("D:\\Go");
                nativeFileSystemFactory.setCreateHome(true);
                sshd.setFileSystemFactory(nativeFileSystemFactory);*/
                System.out.println(serverSession.getClientAddress());
                return true;
            }

        });
        sshd.setKeyPairProvider (new SimpleGeneratorHostKeyProvider (Paths.get("hostkey.ser")));
        sshd.start();
        Thread.sleep(Long.MAX_VALUE);
    }
}